var jsonObj; 
var appKey = "4238391933";
var appSecret = "be4dc3c26087df015f70c1fd860186eb";
// var redirectUrl = "http://hellonima.sinaapp.com/callback.php";
var redirectUrl = "http://hellonima.sinaapp.com/jsonformat.php";
var tempNode;
var weatherNode;
var windNode;
var mainCode;
var latlng;
// list.html初始化函数
function init1() {
	// $.mobile.showPageLoadingMsg("c", "Loading...", true);
	document.addEventListener("deviceready", loadRssChannelTemp, true);
}
// myChannel.html初始化函数
function init2() {
	document.addEventListener("deviceready", loadMyChannelTemp, true);
}
// option.html初始化函数
function init3() {
	document.addEventListener("deviceready", loadConfig_option, true);
}
// about.html初始化函数
function init4() {
	document.addEventListener("deviceready", loadConfig_about, true);
}
// info.html初始化函数
function init5() {
	document.addEventListener("deviceready", loadConfig_info, true);
}
// grant.html初始化函数
function init6() { 
	document.addEventListener("deviceready", loadConfig_grant, true);
}
function loadConfig_grant() {
	document.addEventListener("backbutton", function() {
		window.location.href = "info.html";
	}, true);
	$.mobile.showPageLoadingMsg("a", "Loading...", true);
	loadConfig_list();
	mainCode=localStorage.mainCode;
	if(!mainCode){
		// OAUTH授权页面
		var url = "https://api.weibo.com/oauth2/authorize?response_type=code&"
				+ "client_id=" + appKey + "&redirect_uri=" + redirectUrl
				+ "&display=mobile";
	
		// iframe中显示新浪微博授权页面
		$("#grant").attr("src", url);
		window.onmessage = function(e) {    
			var json_str=e.data;  
			var json_arr=json_str.split("-");
			mainCode=json_arr[0];
			if(mainCode!="http://hellonima.sinaapp.com/jsonformat.php"){
				localStorage.setItem("mainCode",mainCode);
				localStorage.setItem("uid",json_arr[1]);
				showPostWeiboPage();			
			}else{
				window.location.href="info.html";
			}
			// $("#grant").attr("src",postUrl);
		}; 
	}else{
		showPostWeiboPage();
	}
	$.mobile.hidePageLoadingMsg();
}
// 在grant.html页面中展示位发微薄的页面
function showPostWeiboPage(){
	var postUrlStr=localStorage.url.replace(/http:\/\/[\s\S]*src=/,"");
	var postUrl= decodeURIComponent(postUrlStr);
	postUrl="http://"+postUrl+" ";
	var areaContent=postUrl+" (分享新闻)";
	$("#textarea").attr("value",areaContent);
	var uid=localStorage.uid;
	getMyUserInfo(mainCode,uid); 
	$("#grant").attr("src","http://hellonima.sinaapp.com/weibolist.php?access_token="+mainCode);
	$('#grant').css({'width' : $(window).width()}); 
	$("#postArea").css("display","block");
}

function logoutWeibo(){
	localStorage.setItem("mainCode","");
	localStorage.setItem("uid","");
	window.location.href="info.html";
}
function getMyUserInfo(code,uid){
	$.ajax({
		type:"GET",
		url:"https://api.weibo.com/2/users/show.json",
		data:"access_token="+code+"&uid="+uid,
		success:function(msg){
			//alert(msg);
			$("#userInfo").append(msg.name+",您好！");
		},
		error:function(){
			$("#userInfo").append(uid);;
		}
	});
}

//在grant.html页面，点击文本框下的发送按钮，发送新浪微博
function postWeibo(){
	var word=$("#textarea").attr("value");
	word=encodeURI(word);
	$.ajax({
		   type:"POST",
		   url:"https://api.weibo.com/2/statuses/update.json",
		   data:"access_token="+mainCode+"&status="+word,
		   success:function(msg){
				$("textarea").attr("value","");
				$("#grant").attr("src","http://hellonima.sinaapp.com/weibolist.php?access_token="+mainCode);
				navigator.notification.confirm('微博发送成功！', // message
						function(button){
	   				}	, // callback function
	   				'提示', // title
	   				'确定' // confirm 选项，用逗号隔开
				);   
		   },
		   error:function(){
			   navigator.notification.confirm('微博发送失败！\n可能是如下原因所致：\n1.超过会话时间，请重新登录\n2.与上次所发博文内容重复\n3.网络连接不畅', // message
						function(button){
			   			}	, // callback function
						'警告', // title
						'确定' // confirm 选项，用逗号隔开
						);
		   }    
	});  	 
}
//在grant.html页面，点击文本框下的重写按钮，重写文本框里的内容
function clearTextArea(){
	navigator.notification.confirm('确定要清空文本框中内容？', // message
			function(button){
				if(button===1){
					$("textarea").attr("value","");
				}
   			}	, // callback function
			'警告', // title
			'确定,取消' // confirm 选项，用逗号隔开
			);
}

function onBackKeyDown() {
	showConfirm();
	// navigator.app.exitApp();
}
// 页面初始化
function loadConfig_info() {
	document.addEventListener("backbutton", function() {
		window.location.href = "list.html"
	}, true);
	$.mobile.showPageLoadingMsg("c", "Loading...", true);
	loadConfig_list();
	//调用phonegap文件API
	window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,onFileSystemSuccess, fail);
	$.mobile.hidePageLoadingMsg();
}
//phonegap FILE api 失败的回调函数
function fail(evt) {
    console.log(evt.target.error.code);
}
//phonegap FILE api 成功的回调函数
function onFileSystemSuccess(fileSystem) {
    //alert(fileSystem.name);
    //alert(fileSystem.root.name);
   /* var uri =  fileSystem.root.toURL().toString();
   uri= uri.replace(/file\:\/\/localhost/,"");
    alert(uri);*/
    var fileTransfer = new FileTransfer();
	var uri = localStorage.url;
	//gate___baidu___com---tc?bd_page_type=4&src=news___sohu___com%2F20120725%2Fn348976407___shtml.html
	var filePath = fileSystem.root.toURL().toString();
    filePath = filePath.replace(/file\:\/\//,"");
    filePath+="/";
    filePath+= localStorage.filename;
//    filePath+=".html";
    var filename =  localStorage.filename;
//    filename=filename.replace(/gate___baidu___com---tc?bd_page_type=4&src=/,"");
//    filename+=".html";
        fileSystem.root.getFile(filename, null,
        function(fileEntry){
          var reader = new FileReader();
          reader.onloadend = function(evt) {
                var content = evt.target.result;
                $("#newscatch").html(content); 
                $("base").attr("href","");
                $(".trans").hide();
                $(".footer").hide();
                $("#newsUrl").hide();
                var picShow=localStorage["picShow"];
                                if(picShow != "1"){
                                $("img").hide();
                                }
                                //$("div").empty();
           };
           reader.readAsText(fileEntry);
            finishProcess("从缓存中读取新闻");
        },
        function(){
           //$("#newsUrl").attr("src",localStorage.url);
        	window.plugins.fileDownloadAndroid07API.download(
        			 function(data) {
        				 var linkid = localStorage.src.replace(/http\:\/\//, "").replace(/\./g,"___").replace(/\//g, "---");
        				 localStorage.setItem(linkid,"1");  
        				 finishProcess("缓存完成，可离线阅读");
        	               fileSystem.root.getFile(filename, null,
        	                                       function(fileEntry){
        	                                        var reader = new FileReader();
        	                                       reader.onloadend = function(evt) {
        	                                       var content = evt.target.result;
        	                                       $("#newscatch").html(content); 
        	                                       $("base").attr("href","");
        	                                       $(".trans").hide();
        	                                       $(".footer").hide();
        	                                       $("#newsUrl").hide();
        	                                       var picShow=localStorage["picShow"];
        	                                       if(picShow != "1"){
        	                                            $("img").hide();
        	                                       }
        	                                       //$("div").empty();
        	                                       };
        	                                       reader.readAsText(fileEntry);
        	                                       },function(){
        	                                       
        	                                       });
        	               
        	             },
        	             function(error) {
        	   			  alert("网络异常，请重新加载");
        	   			 finishProcess("读取失败");
        	   			$.mobile.hidePageLoadingMsg();
        	   			  //alert("download error target " + error.target);
        	   			 // alert("upload error code" + JSON.stringify(error));
        	   		     }, uri,filePath);
          /* fileTransfer.download(
		     uri,
		     filePath,
		     function(entry) {
			   finishProcess("缓存完成，可离线阅读");
               fileSystem.root.getFile(filename, null,
                                       function(fileEntry){
                                        var reader = new FileReader();
                                       reader.onloadend = function(evt) {
                                       var content = evt.target.result;
                                       $("#newscatch").html(content); 
                                       $("base").attr("href","");
                                       $(".trans").hide();
                                       $(".footer").hide();
                                       $("#newsUrl").hide();
                                       var picShow=localStorage["picShow"];
                                       if(picShow != "1"){
                                            $("img").hide();
                                       }
                                       //$("div").empty();
                                       };
                                       reader.readAsText(fileEntry);
                                       },function(){
                                       
                                       });
               
             },
		     function(error) {
			  alert("网络异常，读取失败：" + error.source);
			  //alert("download error target " + error.target);
			  alert("upload error code" + JSON.stringify(error));
		     }
          );    */                                                         
     });
    
	
}

// 页面初始化
function loadRssChannelTemp() {
	document.addEventListener("backbutton", onBackKeyDown, true);
	onDeviceReady();
	loadConfig_list();
	loadRssChannel();
	checkConnection();
	// 页面加载完成，读取几个必要的节点的值作为变量，供后续代码使用
	tempNode=document.getElementById("temp");
	weatherNode=document.getElementById("weather");
	windNode=document.getElementById("wind");
}

// 加载我的订阅的中介函数，其中还调用了处理页面皮肤的功能
function loadMyChannelTemp() { 
	document.addEventListener("backbutton", onBackKeyDown, true);
	loadConfig_list();
	loadMyChannel();
}
// 获取网站的ico图标
function geticoExt(url) {
	var icoUrl;
	if (url.indexOf(".com/") != -1) {
		icoUrl = url.substring(0, url.indexOf(".com/") + 5);
	} else if (url.indexOf(".cn/") != -1) {
		icoUrl = url.substring(0, url.indexOf(".cn/") + 4);
	} else if (url.indexOf(".net/") != -1) {
		icoUrl = url.substring(0, url.indexOf(".net/") + 5);
	} else if (url.indexOf(".org/") != -1) {
		icoUrl = url.substring(0, url.indexOf(".org/") + 5);
	}
	icoUrl += "favicon.ico";
	return icoUrl;
}
// 读取rss配置文件
function loadRssChannel() {
	// 执行java插件成功后的函数

	var success = function(data) {
		jsonObj = data;
		localStorage.channel=JSON.stringify(data);
		var length = jsonObj.length;

		var show = "";
		var reflushString = "刷新频道";
		// alert(data[0].enable+" "+(data[0].enable==true?"t":"f"));
		for ( var i = 0; i < length; i++) {
			if (data[i].enable) {
				var temp = data[i].url.replace(/http\:\/\//, "").replace(/\./g,
						"___").replace(/\//g, "---");
				show += "<div data-role='collapsible' id='";
				show += temp;
				show += "'><h4>";
				var icon = geticoExt(data[i].url);
				show += "<img src='" + icon + "'/>";

				show += data[i].name;
				show += "</h4><ul data-role='listview' data-inset='false' data-divider-theme='b' id='";
				show += temp;
				show += "'><li class='list-item-schedule' data-theme='c' data-icon='refresh'><a href='#' onclick='loadRss(&#39;";
				show += data[i].url;
				show += "&#39;);'><div align='center'>" + reflushString
						+ "</div></a></li></ul></div>";
			}
		}
		// 加载频道完成之后 读取每个频道的缓存信息
		// showProcess("正在读取缓存...");
		var networkState = navigator.network.connection.type;
		// 如果设备使用的3g网络-判断是否自动更新
		if (Connection.CELL_3G == networkState
				|| Connection.WIFI == networkState) {
			var success = function(dat) {
				// 自动更新
				if (dat.autoFlush == "1") {
					for ( var i = 0; i < length; i++) {
						// $.mobile.showPageLoadingMsg("a","正在刷新"+data[i].url,true);
						if (data[i].enable) {
							loadRss(data[i].url);
						}
						// $.mobile.hidePageLoadingMsg ();
					}
				} else {
					// 读缓存
					for ( var i = 0; i < length; i++) {
						if (data[i].enable) {
							loadRssCatch(data[i].url);
						}
					}
				}
			}
			window.plugins.loadConfigAndroid05API.loadconfig(success, error,
					null);
		} else {
			// 2G网络读缓存
			for ( var i = 0; i < length; i++) {
				if (data[i].enable) {
					loadRssCatch(data[i].url);
				}
			}
		}

		$("#channelList").html(show);
		$("#channelList").trigger('create');
		finishProcess("启动完成");

	};
	var error = function(e) {
		errorProcess("启动失败,请检查配置");
	};

	window.plugins.loadChannnelAndroid01API.loadChannel(success, error, null);
}
// 读取配置文件中频道信息
function loadMyChannel() {
	$.mobile.showPageLoadingMsg("a", "Loading...", true);
	var success = function(data) {
		var length = data.length; 

		// var show = '<ul data-inset="true" data-splittheme="a" >';
		var show = '';
		for ( var i = length-1; i >=0 ; i--) {
			show += '<div  class="li_entire"><div class="li_left"><h3>';
			show += data[i].name;
			show += '</h3><p><a href="';
			show += data[i].url;
			show += '" >';
			show += data[i].url;
			show += '</a></p></div><div class="li_center"><div data-role="fieldcontain" align="center"><label for="slider">订阅状态:</label><select name="slider" id="';
			show += data[i].url;
			show += '" onchange="stateChange(this);"><option value="off">未订</option><option value="on">已订</option></select></div></div></div>';
			// show += '</a></p></div><div class="li_center"><div
			// data-role="fieldcontain"><fieldset
			// data-role="controlgroup"><legend>订阅状态</legend><input
			// type="checkbox" name="checkbox-1" id="checkbox-1" class="custom"
			// /><label for="checkbox-1">订阅</label></fieldset></div></div>';
		}
		// show += '</ul>';

		$("#channelList").html(show);
		var myswitch = $("select");
		for ( var i = length-1; i >=0 ; i--) {
			if (data[i].enable) {
				myswitch[length-1-i].selectedIndex = 1;
			}
		} 

		$("#channelList").trigger('create');
		$.mobile.hidePageLoadingMsg();
	};
	var error = function(e) {

	};
	window.plugins.loadChannnelAndroid01API.loadChannel(success, error, null);

}
// 更改频道的订阅状态
function stateChange(event) {
	// alert(event.id);
	// alert(event.selectedIndex);
	var url = event.id;
	var state = false;
	if (event.selectedIndex) {
		state = true;
	} else {
		state = false;
	}

	updateChannel(url, state);
}
//增加阅读源
function add(){
    var name = $("#input_name").attr("value");
    var rss = $("#input_url").attr("value");
    window.plugins.addChannelAndroid08API.add(
    		function(){
		    	$("#channelInput").attr("style","display: none;border:solid");
		    	loadMyChannel();
		    
    		}, null,name,rss);
//    $("#channelInput").attr("style","display: none;border:solid");
//    loadMyChannel();
}
//show input
function showInput(){
    $("#channelInput").attr("style","display: block;border:solid;border-color:gray;border-radius: 15px 15px 15px 15px;");

}

function flushStateChange(event) {
	// alert(event.checked);
	if (event.checked) {
		updateConfig("autoFlush", 1);
	} else {
		updateConfig("autoFlush", 0);
	}

}
//代理开关改变
function proxyStateChange(event) {
	// alert(event.checked);
	if (event.checked) {
		updateConfig("proxy", 1);
		$("#ip").removeAttr("disabled");
		$("#port").removeAttr("disabled");
		
	} else {
		updateConfig("proxy", 0);
		$("#ip").attr("disabled","disabled");
		$("#port").attr("disabled","disabled");
	}

}
//代理ip改变
function ipStateChange(event){
	var value = event.value;
	updateConfig("ip",value);
}
//代理port改变
function portStateChange(event){
	var value = event.value;
	updateConfig("port",value);
}
// 主题状态修改，将状态写入配置文件中
// option.html中的选择菜单中调用该函数
function themeStateChange(event) {
	var num = event.selectedIndex + 97;
	var themeId = String.fromCharCode(num);
	updateConfig("theme", themeId);
	// 状态修改完成后，再刷新本页面的主题样式
	loadConfig_option();

}

// 修改rss源配置文件-更新频道的订阅状态
function updateChannel(url, enable) {
	// 修改成功后的操作
	var success = function() {
	}
	// 修改失败后的操作
	var error = function(e) {
	}
	window.plugins.loadChannnelManagerAndroid04API.channelManager(success,
			error, url, enable);
}

function getRealUrl(url) {
	var urlReal = url.replace(/---/g, "/").replace(/___/g, ".");
	return urlReal = "http://" + urlReal;
}

// 读取rss具体信息
function loadRss(url) {
	// 状态栏显示正在加载
	// showProcess("正在加载...");
	$.mobile.showPageLoadingMsg("c", "正在刷新请稍后", true);
	// 执行java插件成功后的函数
	var success = function(data) {
		// 状态栏显示完成加载
		// finishProcess("加载完成");
		$.mobile.hidePageLoadingMsg();
		var length = data.length;

		var show = "<li class='list-item-schedule' data-theme='c' data-icon'refresh'><a href='#' onclick='loadRss(&#39;";
		show += url;
		show += "&#39;);'><div align='center'>刷新频道</div></a></li>";
		;
		for ( var i = 0; i < length; i++) {
			var temp = data[i].description.replace(/<\/a>/, "").replace(
					/<a.*html'>/, "");
			show += '<li class="list-item-schedule" data-theme="c"><a href="#" onclick=go(&#39;';
			show += data[i].link;
			show += '&#39;)><div class="list-item-content-schedule"><h4>';
			show += data[i].title;
			show += '</h4><p class="session-time-speaker">';
			show += data[i].pubDate;
			show += '</p><p>';
			show += temp;
			show += '</p></div></a></li>';
		}
		// alert(11);
		// alert(show);
		url = url.replace(/http\:\/\//, "").replace(/\./g, "___").replace(
				/\//g, "---");
		// alert(url);
		// url="http://news.163.com/special/00011K6L/rss_newstop.xml"
		$("ul#" + url).html(show);
		$("ul#" + url).listview('refresh');
		saveToDataBase(url,data);
	};
	var error = function(e) {
		// errorProcess("加载失败,请检查网络");
		$.mobile.hidePageLoadingMsg();
		alert("加载失败,请检查网络" + url);

	};

	window.plugins.loadRssAndroid02API.loadRss(success, error, url);
}
// 读取rss缓存
function loadRssCatch(url) {
	// 执行java插件成功后的函数
	var success = function(data) {
		var length = data.length;

		var show = '';
		// alert(data[1].title);
		for ( var i = 0; i < length; i++) {
			var temp = data[i].description.replace(/<\/a>/, "").replace(
					/<a.*html'>/, "");
			show += '<li class="list-item-schedule" data-theme="c"><a href="#" onclick=go(&#39;';
			show += data[i].link;
			// show+="info.html";
			show += '&#39;)><div class="list-item-content-schedule"><h4>';
			show += data[i].title;
			show += '</h4><p class="session-time-speaker">';
			show += data[i].pubDate;
			show += '</p><p>';
			show += temp;
			show += '</p></div></a></li>';
		}
		// alert(11);
		// alert(show);
		url = url.replace(/http\:\/\//, "").replace(/\./g, "___").replace(
				/\//g, "---");
		// alert(url);
		// url="http://news.163.com/special/00011K6L/rss_newstop.xml"
		$("ul#" + url).append(show);
		$("ul#" + url).listview('refresh');
	};
	var error = function(e) {
		alert()
	};

	window.plugins.loadRssCatchAndroid03API.loadRssCatch(success, error, url);
}
//save to database
function saveToDataBase(url,data){
    var length = data.length;
    var catch1 ="[{";
    for ( var i = 0; i < length; i++) {  
        var title = data[i].title;
        var link = data[i].link; 
        var description = data[i].description.replace(/<\/a>/, "").replace(
            /<a.*html'>/, "");
        //description =htmlEncode(description);
        var updated = data[i].updated;
       /* executeSql('INSERT INTO RSSCATCH (url,title,link,description,updated) VALUES ("'+url+'","'+title+'","'+link+'","'+description+'","'+updated+'")');*/
        catch1 += "title:'"+title+"',link:'"+link+"',description:'dpt',updated:'"+updated+"'}";
        if(i!=length-1){
           catch1+=",{";              
        }else{
           catch1+="]";              
        }
        
    }
    //alert(catch1); 
    var json = eval(catch1);
   // alert(json.length);  
    localStorage.setItem("catch_"+url,catch1);
    var key = "catch_"+url;
                  
    //alert(localStorage[key]);
  //  alert(key+" "+json[0].title);
}
// 读取系统配置文件
// 对设置页面option.html
function loadConfig_option() {
	document.addEventListener("backbutton", onBackKeyDown, true);
	var success = function(data) {
		// var msg = "";

		// msg +="autoFlush(自动刷新):"+ data.autoFlush+"\n";
		// msg +="theme(主题):"+data.theme;

		// var mySet=$("#baseSet");
		if (data.autoFlush == "1") {
			$("#autoFlush").attr("checked", true).checkboxradio(
					"refresh");
		}
		if(localStorage.picShow=="1"){
            $("#picShow").attr("checked", true).checkboxradio("refresh"); 
        }
		if(data.proxy=="1"){
			$("#proxy").attr("checked", true).checkboxradio(
			"refresh");
			$("#ip").removeAttr("disabled");
			$("#port").removeAttr("disabled");
		}else{
			$("#ip").attr("disabled","disabled");
			$("#port").attr("disabled","disabled");
		}
		
		$("#ip").attr("value",data.ip);
		$("#port").attr("value",data.port);
		var index = data.theme.charCodeAt() - 97;
		var myselect = $("select#selectTheme");
		myselect[0].selectedIndex = index;
		myselect.selectmenu("refresh");

		changeTheme(data.theme);
	}
	var error = function(e) {
	}
	window.plugins.loadConfigAndroid05API.loadconfig(success, error, null);

}
//显示图片设置改变
function picStateChange(event) {
	// alert(event.checked);
	if (event.checked) {
		localStorage.setItem("picShow", 1);
	} else {
		localStorage.setItem("picShow", 0);
	}
    
}
// 读取系统配置文件
// 对设置页面about.html
function loadConfig_about() {
	document.addEventListener("backbutton", onBackKeyDown, true);
	var success = function(data) {
		// var msg = "";

		// msg +="autoFlush(自动刷新):"+ data.autoFlush+"\n";
		// msg +="theme(主题):"+data.theme;

		// var mySet=$("#baseSet");
		// if(data.autoFlush=="1"){
		// $("input[type='checkbox']").attr("checked",true).checkboxradio("refresh");
		// }

		// var index = data.theme.charCodeAt() - 97;
		// var myselect=$("select#selectTheme");
		// myselect[0].selectedIndex = index;
		// myselect.selectmenu("refresh");

		changeTheme(data.theme);
	}
	var error = function(e) {
	}
	window.plugins.loadConfigAndroid05API.loadconfig(success, error, null);

}
// 读取系统配置文件
// 更换主题list.html
function loadConfig_list() {
	var success = function(data) {
		// var msg = "";

		// msg +="autoFlush(自动刷新):"+ data.autoFlush+"\n";
		// msg +="theme(主题):"+data.theme;

		// var mySet=$("#baseSet");
		// if(data.autoFlush=="1"){
		// $("input[type='checkbox']").attr("checked",true).checkboxradio("refresh");
		// }

		var index = data.theme.charCodeAt() - 97;

		changeTheme(data.theme);
	}
	var error = function(e) {
	}
	window.plugins.loadConfigAndroid05API.loadconfig(success, error, null);

}

// 更新系统配置文件
function updateConfig(key, value) {
	var success = function(data) {

	}
	var error = function(e) {
	}
	window.plugins.updateConfigAndroid06API.updateConfig(success, error, key,
			value);
}

function go(url) {
	var baiduzm = "http://gate.baidu.com/tc?bd_page_type=4&src=";
	var src = url.replace(/http\:\/\//, "").replace(/\//g, "%2F");
	// 设备的网络
	var networkState = navigator.network.connection.type;
	// window.location.href = url;
	// 如果设备使用的2g网络
	
		// 将新闻地址存储到本地html
		localStorage.url = baiduzm + src;
		localStorage.src = url;
		localStorage.filename = src;
		$.mobile.showPageLoadingMsg("c", "Loading...", true);
		window.location.href = "info.html";
	
}

function onConfirm(button) {

	// if press 'Yes'
	if (button === 1) {
		//程序结束时，将本次登录新浪微博所需的access_token和uid置为空
		localStorage.mainCode="";
		localStorage.uid="";
		localStorage.conns="";
		localStorage.netState="";
		navigator.app.exitApp();
	}
}

// PhoneGap Notification 提供的 Confirm API
function showConfirm() {
	navigator.notification.confirm('确定要退出程序吗?', // message
	onConfirm, // callback function
	'关闭提示', // title
	'确定,取消' // confirm 选项，用逗号隔开
	);
}

/*
 * $("div[data-role=collapsible]").live("click",function(){ loadRss(this.id);
 * alert(this.id); });
 */
// 显示加载动画
function showProcess(msg) {
	if (msg == null) {
		msg = "loading";
	}

	$("#message").html(msg);
	$("#message").trigger('create');
	$("#messagePic").attr("src", "../css/images/loading.gif");
	$("#messagePic").animate({
		src : "../css/images/loading1001.jpg"
	}, "slow");
	$("#messagePic").animate({
		src : "../css/images/loading1003.jpg"
	}, "slow");
	$("#messagePic").animate({
		src : "../css/images/loading1005.jpg"
	}, "slow");
	$("#messagePic").animate({
		src : "../css/images/loading1007.jpg"
	}, "slow");
	$("#messagePic").animate({
		src : "../css/images/loading1009.jpg"
	}, "slow");
	$("#messagePic").animate({
		src : "../css/images/loading10011.jpg"
	}, "slow");
	$("#messagePic").animate({
		src : "../css/images/loading10013.jpg"
	}, "slow");
	$("#messagePic").animate({
		src : "../css/images/loading10015.jpg"
	}, "slow");
	$("#messageFrame").fadeIn(2000);

}
// 完成加载动画
function finishProcess(msg) {
	if (msg == null) {
		msg = "finish";
	}
	$("#messagePic").attr("src", "../css/images/finish.png");
	$("#message").html(msg);
	$("#messageFrame").fadeOut(2000);
}
// 出错加载动画
function errorProcess(msg) {
	if (msg == null) {
		msg = "error";
	}
	$("#messagePic").attr("src", "../css/images/error.png");
	$("#message").html(msg);
	$("#messageFrame").fadeOut(2000);
}
// 隐藏状态栏
function hideProcess() {
	$("#messageFrame").hide();
}
// 更换主题
function changeTheme(id) {

	changeTheme_body(id);
	changeTheme_header(id);
	changeTheme_footer(id);
	changeTheme_btn(id);
	$("body").attr("style", "display:block");

}
// 更换body主题
function changeTheme_body(id) {
	var the = /ui-\w+-\w{1}\s/;
	var s = $("body").attr("class") + "";

	var s1 = the.exec(s) + "";
	if (s1 != null) {
		s1 = s1.replace(/-\w{1}\s/, "-" + id + " ");
		s = s.replace(/ui-\w+-\w{1}\s/, s1);
		// alert(s);
		$("body").attr("class", s);
	}
}

// 更换头部主题
function changeTheme_header(id) {
	var the = /ui-\w+-\w{1}\s/;
	var s = $("div#ui_header").attr("class") + "";

	var s1 = the.exec(s) + "";
	if (s1 != null) {
		s1 = s1.replace(/-\w{1}\s/, "-" + id + " ");
		s = s.replace(/ui-\w+-\w{1}\s/, s1);
		// alert(s);
		$("div#ui_header").attr("class", s);
	}
}
function changeTheme_footer(id) {
	changeTheme_footera(id);
	changeTheme_footerb(id);
	changeTheme_footerc(id);
	changeTheme_footerd(id);
	changeTheme_footere(id);

}
function changeTheme_btn(id) {
	var the = /ui-\w+-\w+-\w{1}\s/;
	var s = $("#head_btn").attr("class") + "";

	var s1 = the.exec(s) + "";
	if (s1 != null) {
		s1 = s1.replace(/-\w{1}\s/, "-" + id + " ");
		s = s.replace(/ui-\w+-\w+-\w{1}\s/, s1);
		// alert(s);
		$("#head_btn").attr("class", s);
	}
	changeTheme_btn1(id)
}
function changeTheme_btn1(id) {
	var the = /ui-\w+-\w+-\w{1}\s/;
	var s = $("#head_btn1").attr("class") + "";

	var s1 = the.exec(s) + "";
	if (s1 != null) {
		s1 = s1.replace(/-\w{1}\s/, "-" + id + " ");
		s = s.replace(/ui-\w+-\w+-\w{1}\s/, s1);
		// alert(s);
		$("#head_btn1").attr("class", s);
	}
}
function changeTheme_footera(id) {
	var the = /ui-\w+-\w+-\w{1}\s/;
	var s = $("a#ui_footera").attr("class") + "";

	var s1 = the.exec(s) + "";
	if (s1 != null) {
		s1 = s1.replace(/-\w{1}\s/, "-" + id + " ");
		s = s.replace(/ui-\w+-\w+-\w{1}\s/, s1);
		// alert(s);
		$("a#ui_footera").attr("class", s);
	}
}
function changeTheme_footerb(id) {
	var the = /ui-\w+-\w+-\w{1}\s/;
	var s = $("a#ui_footerb").attr("class") + "";

	var s1 = the.exec(s) + "";
	if (s1 != null) {
		s1 = s1.replace(/-\w{1}\s/, "-" + id + " ");
		s = s.replace(/ui-\w+-\w+-\w{1}\s/, s1);
		// alert(s);
		$("a#ui_footerb").attr("class", s);
	}
}
function changeTheme_footerc(id) {
	var the = /ui-\w+-\w+-\w{1}\s/;
	var s = $("a#ui_footerc").attr("class") + "";

	var s1 = the.exec(s) + "";
	if (s1 != null) {
		s1 = s1.replace(/-\w{1}\s/, "-" + id + " ");
		s = s.replace(/ui-\w+-\w+-\w{1}\s/, s1);
		// alert(s);
		$("a#ui_footerc").attr("class", s);
	}
}
function changeTheme_footerd(id) {
	var the = /ui-\w+-\w+-\w{1}\s/;
	var s = $("a#ui_footerd").attr("class") + "";

	var s1 = the.exec(s) + "";
	if (s1 != null) {
		s1 = s1.replace(/-\w{1}\s/, "-" + id + " ");
		s = s.replace(/ui-\w+-\w+-\w{1}\s/, s1);
		// alert(s);
		$("a#ui_footerd").attr("class", s);
	}
}
function changeTheme_footere(id) {
	var the = /ui-\w+-\w+-\w{1}\s/;
	var s = $("a#ui_footere").attr("class") + "";
    
	var s1 = the.exec(s) + "";
	if (s1 != null) {
		s1 = s1.replace(/-\w{1}\s/, "-" + id + " ");
		s = s.replace(/ui-\w+-\w+-\w{1}\s/, s1);
		// alert(s);
		$("a#ui_footere").attr("class", s);
	}
}
// new content
// 通过移动设备的经纬度获得用户所在地的市级地名
function getCity(latlng) {
	if(!latlng || latlng == null){
		latlng="32.046497,118.777313";
	}
	
	$.ajax({
		type:"get",
    	url:"http://maps.googleapis.com/maps/api/geocode/json", 
		data:{
			latlng : latlng,
			sensor : "true"
		},
		success:function(data) { 
			var cityname = "";
			//json = eval("(" + data + ")");
			var jsonData=data;
			if(jsonData.status=="OK"){
				for ( var i in jsonData.results[0].address_components) {
					if (jsonData.results[0].address_components[i].types[0] == "locality") {
						cityname = jsonData.results[0].address_components[i].long_name;
						break;
					}
				}
			}else{
				cityname="南京";
			}
			if(cityname.length>5){
				$("#cityname").css("font-size","24px");
			}else if(cityname.length>2){
				$("#cityname").css("font-size","29px");
			}
			var cityNode=document.getElementById("cityname");
			cityNode.innerHTML=cityname;
			getWeatherInfo(cityname);
		},
		error:function(){
			var cityname="南京";
			var cityNode=document.getElementById("cityname");
			cityNode.innerHTML=cityname;
			getWeatherInfo(cityname);
		}
	}, "text");

}

// 通过城市名得到未来5天的天气数据
function getWeatherInfo(cityname){
	var cityid;
	var citykey=cityname.replace(" ","_");
	 try{
	        cityid=eval("obj."+citykey);
	    //alert(cityid);
	    }catch(error){
	        if(!cityid){
	            cityid="101190101";
	        }
	    }
	    if(!cityid){
	        
	        cityid="101190101";
	    }
	var url="http://m.weather.com.cn/data/"+cityid+".html";
	// alert(url);
	$.get(url,function(data){
		alterNowWeatherData(data);
	},"text"); 
}
// 根据最新数据，修改程序中，关于天气信息的数据
function alterNowWeatherData(data){
	var data=eval("("+data+")");
	tempNode.innerHTML=data.weatherinfo.temp1;
	weatherNode.innerHTML=data.weatherinfo.weather1;
	windNode.innerHTML=data.weatherinfo.wind1;
	
	var imageUrl="../css/images/weather/"+eval("imagesObj."+data.weatherinfo.img_title1);
	
	$("#weather_image").css("background","url("+imageUrl+") no-repeat");
}

function onDeviceReady() {
	// 设备主板就绪后，读取文件中的配置文件
	// window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
	// 设备准备就绪后，查询当前地理位置
	navigator.geolocation.getCurrentPosition(onPosSuccess, onPosError);
}
// 成功获取文件系统的回调函数
function gotFS(fileSystem) {  
	fileSystem.root.getFile("xxx.txt", null, gotFileEntry, fail);
}
// 获得文件实体成功后的回调函数 
function gotFileEntry(fileEntry) {
	fileEntry.file(gotFile, fail);
}
// 获得文件成功后的回调函数
function gotFile(file) {

	readAsText(file);
}
// 以文本格式读取文件内容
function readAsText(file) {
	var reader = new FileReader();

	// 读取成功的回调函数
	reader.onloadend = function(evt) {
		console.log("Read as text");
		// console.log(evt.target.result);
		alert(evt.target.result);
	};

	reader.readAsText(file);
}
// 出现错误的回调函数
function fail(evt) {
	// console.log(evt.target.error.code);
	if(evt.code==1){
		var word="程序所需的配置文件未能被找到!\n\n"+
				"请尝试选择以下方法解决:\n"+
				"1.重新运行程序再次尝试加载文件\n"+
				"2.手动还原曾经转移、删除或者重命名的文件\n"+
				"3.或许您需要重新安装程序";
		navigator.notification.confirm(word, // message
				// onConfirm, // callback function
				null,
				'警告!', // title
				'确定' // confirm 选项，用逗号隔开
				);
	}
}

// onSuccess Geolocation
// onSuccess获取当前位置成功时的回调函数
function onPosSuccess(position) {
	
	latlng = position.coords.latitude + "," + position.coords.longitude;
	//latlng="34.284453,108.232498";
	// var latlng="42.60162,122.76123"; //辽宁省阜新市彰武县
	//latlng="37.775057,-122.412415";	//旧金山
	//latlng="38.91027,-77.063599";	//华盛顿哥伦比亚特区
	//latlng="42.358798,-71.05957";//波士顿
	//latlng="25.788763,-80.224228"; //迈阿密
	//latlng="28.549545,-81.392212";	//奥兰多
	//latlng="33.748322,-84.37912";	//亚特兰大
	//latlng="34.050384,-118.251343";	//洛杉矶
	// 芝加哥   41.911475,-87.666779
	// 西雅图   47.6057,-122.310791
	// 纽约  40.712915,-73.987427
	// 休斯顿  29.802518,-95.372314
	// 拉斯维加斯  36.099048,-115.109253
	//latlng="36.099048,-115.109253";
	// 檀香山 21.313045,-157.848816
	//latlng="28.6448,77.203674";		//新德里
	getCity(latlng);
}

// onPosError Callback receives a PositionError object
// onPosError获取当前位置失败时的回调函数
function onPosError(error) {
	alert("当前位置获取出现未知异常！\n请不要刻意关闭获取位置信息的服务");
	getCity(latlng)
	//alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
// phoneGap调试函数，在非浏览器下，打印需要watch的obj的属性和值
function testObject(obj) { 
	for ( var i in obj) {
		var props = "";
		// 开始遍历
		for ( var p in obj) {
			// 方法
			if (typeof (obj[p]) == " function ") {
				// obj [ p ]() ;
			} else {
				// p 为属性名称，obj[p]为对应属性的值
				props += p + " = " + obj[p] + " \t ";
			}
		}
		// 最后显示所有的属性
		alert(props);
	}

}

function test1(){
	
	alert(1);
}

function checkConnection(){
	if(!localStorage.conns){
		localStorage.conns=1;
	}
	if(localStorage.conns==1){
		var networkState = navigator.network.connection.type;
		
		var states={};
		states[Connection.UNKNOWN]  = 'Unknown connection';
	    states[Connection.ETHERNET] = 'Ethernet connection';
	    states[Connection.WIFI]     = 'WiFi connection';
	    states[Connection.CELL_2G]  = 'Cell 2G connection';
	    states[Connection.CELL_3G]  = 'Cell 3G connection';
	    states[Connection.CELL_4G]  = 'Cell 4G connection';
	    states[Connection.NONE]     = 'No network connection';
	   // alert('Connection type:'+states[networkState]);
	    if(networkState==Connection.NONE){
	    	 navigator.notification.alert(
	    	            '您当前没有网络连接!!\n      仅能使用离线阅读等部分功\n能，为了获得更好的用户体验，\n推荐使用wifi网络。',  // message
	    	            function(){},         // callback
	    	            '网络连接:',            // title
	    	            '确定'                  // buttonName
	    	        );	
	    }else if(networkState==Connection.CELL_2G){
	    	 navigator.notification.alert(
	 	            '您当前使用的是2G网络\n      能正常阅读新闻，但部分功能可能会延迟显示或显示异常，为了获得更好的用户体验，推荐使用WIFI网络。',  // message
	 	            function(){},         // callback
	 	            '网络连接:',            // title
	 	            '确定'                  // buttonName
	 	        );	
	    }else{
	    	 navigator.notification.alert( 
	  	            '			有任何意见或建议均可发送邮件至zjfhw100513@gmail.com，我们会在第一时间回复您的信息。\n\n祝您使用愉快\n————一行项目组',  // message
	  	            function(){},         // callback
	  	            '欢迎使用本程序',            // title
	  	            '确定'                  // buttonName
	  	        );	
	    }
	     
	    localStorage.netState=states[networkState];
	    localStorage.conns=0;
	}
	$("#conns").html("Connection status:"+localStorage.netState);
}
